# -*- coding:utf-8 -*-
import settings

RM_SESSION_VARIABLE = "request_messages"
if settings.__dict__.has_key('RM_SESSION_VARIABLE'):
    RM_SESSION_VARIABLE = settings.RM_SESSION_VARIABLE

class RequestMessages:
    """
    User messages objects -- contains 3 fields which are lists. As simple as possible.
    """
    def __init__(self):
        self.notices = []
        self.warnings = []
        self.errors = []

    def __getitem__(self, name):
        if name == 'notices':
            return self.notices
        elif name == 'warnings':
            return self.warnings
        elif name == 'errors':
            return self.errors
        else:
            raise KeyError("Unknown key %s." % name)

    def __setitem__(self, name, value):
        """
        Value should be list
        """
        if name == 'notices':
            self.notices = value
        elif name == 'warnings':
            self.warnings = value
        elif name == 'errors':
            self.errors = value
        else:
            raise KeyError("Unknown key %s." % name)

    def __len__(self):
        return len(self.notices) + len(self.warnings) + len(self.errors)


class RequestMessageMiddleware:
    def process_request(self, request):
        """
        Create request.messages -- RequestMessages object received from session or new one
        """
        request.messages = RequestMessages()
        if request.session.has_key(RM_SESSION_VARIABLE):
            request.messages = request.session[RM_SESSION_VARIABLE]
            request.session['RM_SESSION_VARIABLE'] = RequestMessages()
        if request.messages is None:
            request.messages = RequestMessages()
        return None

    def process_response(self, request, response):
        """
        If response is redirection it adds request messages to session. If there is no message it switch request messages to None value to use it in templates.
        """
        if request.__dict__.has_key('messages'):
            response_name = response.__class__.__name__
            if response_name == 'HttpResponseRedirect' or response_name == 'HttpResponsePermanentRedirect':
                request.session[RM_SESSION_VARIABLE] = request.messages
            else:
                request.session[RM_SESSION_VARIABLE] = RequestMessages()
            if len(request.messages) == 0:
                request.messages = None
        else:
            request.messages = None
        return response
